function formatMoney(val) {
	var str = (val / 100).toFixed(2) + '';
	var intSum = str.substring(0, str.indexOf(".")).replace(/\B(?=(?:\d{3})+$)/g, ',');
	var dot = str.substring(str.length, str.indexOf("."))
	var ret = intSum + dot;
	return ret;
}


function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatDateTime(date, fmt = 'yyyy-MM-dd hh:mm:ss') {
	if (!date) {
		return ''
	}
	if (typeof(date) === 'number') {
		date = new Date(date * 1000)
	}
	var o = {
		"M+": date.getMonth() + 1, //月份
		"d+": date.getDate(), //日
		"h+": date.getHours(), //小时
		"m+": date.getMinutes(), //分
		"s+": date.getSeconds(), //秒
		"q+": Math.floor((date.getMonth() + 3) / 3), //季度
		"S": date.getMilliseconds() //毫秒
	}
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length))
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k])
				.length)))
	return fmt
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}

var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDate()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};


function getLocation() {
	return new Promise((resolve, reject) => {
		uni.authorize({
			scope: 'scope.userLocation',
			success: (res) => {
				uni.getLocation({
					type: 'gcj02',
					success: result => {
						resolve(result)
					},
					fail: (res) => {
						uni.showModal({
							title: '提示',
							content: '请先开启手机GPS定位',
							confirmText: '确定'
						});
						reject(res);
					}
				});
			},
			fail: (res) => {
				uni.showModal({
					title: '授权失败',
					content: '贵达物流需要获取你的地理位置，请在设置界面打开相关权限。',
					confirmText: '设置',
					success: res => {
						if (res.confirm) {
							uni.openSetting({
								success: (data) => {
									if (data.authSetting[
											"scope.userLocation"
										] ===
										true) {
										uni.showToast({
											title: '授权成功',
											icon: 'success',
											duration: 1000,
										})
										uni.authorize({
											scope: 'scope.userLocation',
											success: res => {
												uni.getLocation({
													type: 'gcj02',
													success: result => {
														resolve
															(
																result
															)
													},
													fail: res => {
														uni.showModal({
															title: '提示',
															content: '请先开启手机GPS定位',
															confirmText: '确定'
														});
														resolve
															(
																res
															)
													}
												});
											},
										})
									} else {
										uni.showToast({
											title: '授权失败',
											icon: 'none',
											duration: 1000,
										})
									}
								}
							})
						}
					}
				})
			}
		});
	})
}

//获取字符串的真实长度（字节长度）
function strLeng(str) {
	if (str) {
		let len = str.length,
			truelen = 0;
		for (let x = 0; x < len; x++) {
			if (str.charCodeAt(x) > 128) {
				truelen += 2;
			} else {
				truelen += 1;
			}
		}
		return truelen;
	} else {
		return 0;
	}
}
//计算页数
function getPageNum(total, row) {
	let num = Number(total) / Number(row);
	//是否为整数
	if (num % 1 !== 0) {
		let b = num.toString(); //转字符串
		let a = parseInt(b.substring(0, b.indexOf('.'))); //取小数点前
		let s = b.replace(/\d+\.(\d*)/, '$1'); //取小数点后
		if (s > 0) {
			num = a + 1;
		}
	}
	return num;
}
//设置手机通知栏字体颜色
function setBarColor(black = false) {
	if (black) {
		uni.setNavigationBarColor({
			frontColor: '#000000',
			backgroundColor: '#FAFAFA'
		});
	} else {
		uni.setNavigationBarColor({
			frontColor: '#ffffff',
			backgroundColor: '#FAFAFA'
		});
	}
}

module.exports = {
	formatTime,
	formatDateTime,
	formatLocation,
	dateUtils,
	getLocation,
	setBarColor,
	getPageNum,
	strLeng
}
